<!-- 笔记详情 -->
<template>
    <div class="box">
        <div class="top">
            <div class="back" @click="$router.back()">
                <svgIcon iconName="icon-fanhui" font-size="40px"></svgIcon>
            </div>
            <div class="user_pic" >
                <img v-if="userInfo.avatar_url" :src="userInfo.avatar_url" alt="用户头像">
                <img v-else :src="defaultAvatar" alt="默认头像">
            </div>
            <div class="user_name">
                {{ userInfo.nickname || '未设置昵称' }}
            </div>
        </div>
        <div class="content" ref="messageContainer">

            
            <div 
                v-for="(message, index) in messages" 
                :key="index" 
                class="message_container"
            >
                <!-- 对方消息 -->
                <div v-if="message.from !== currentUserId && message.from !== 'me'" class="he_avatar">
                    <img 
                        :src="userInfo.avatar_url || defaultAvatar" 
                        alt="对方头像"
                    >
                </div>
                <div v-if="message.from !== currentUserId && message.from !== 'me'" class="he_item">
                    <div class="message_bubble">
                        <div class="message_text">{{ message.message }}</div>
                        <div class="message_time">{{ formatTime(message.timestamp) }}</div>
                    </div>
                </div>
                
                <!-- 我的消息 -->
                <div v-if="message.from === currentUserId || message.from === 'me'" class="me_item">
                    <div class="message_bubble">
                        <div class="message_text">{{ message.message }}</div>
                        <div class="message_time">{{ formatTime(message.timestamp) }}</div>
                    </div>
                </div>
                <div v-if="message.from === currentUserId || message.from === 'me'" class="me_avatar">
                    <img 
                        :src="currentUserAvatar" 
                        alt="我的头像"
                    >
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="input_area">
                <input 
                    v-model="newMessage" 
                    @keyup.enter="sendMessage"
                    placeholder="输入消息..." 
                    class="message_input"
                />
                <button @click="sendMessage" class="send_btn">发送</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, onUnmounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import svgIcon from '@/components/svgIcon.vue';
import defaultAvatar from '@/assets/czq/pic.png';
import { showToast } from 'vant';
import websocketService from '@/services/websocket';

const route = useRoute();
const userId = computed(() => route.query.userId);
const currentUserId = ref(localStorage.getItem('user_id'));
const messageContainer = ref(null);
const newMessage = ref('');
const socket = ref(null);

// 用户信息
const userInfo = ref({
    nickname: '',
    user_id: '',
    avatar_url: '',
});

// 当前用户头像
const currentUserAvatar = ref(defaultAvatar);

// 消息列表
const messages = ref([]);

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        if (!userId.value) {
            showToast('未获取到用户ID');
            return;
        }

        const response = await axios.get(`http://1.14.98.17:8765/api/users/${userId.value}`);
        if (response.data.success === true) {
            const data = response.data.data;
            userInfo.value = {
                nickname: data.nickname || '未设置昵称',
                user_id: data.user_id || '未设置小红书号',
                avatar_url: data.avatar_url || defaultAvatar,
            };
        } else {
            showToast(response.data.message || '获取用户信息失败');
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        showToast('获取用户信息失败');
    }
};

// 获取当前用户信息
const fetchCurrentUserInfo = async () => {
    try {
        if (!currentUserId.value) {
            return;
        }

        const response = await axios.get(`http://1.14.98.17:8765/api/users/${currentUserId.value}`);
        if (response.data.success === true) {
            const data = response.data.data;
            currentUserAvatar.value = data.avatar_url || defaultAvatar;
        }
    } catch (error) {
        console.error('获取当前用户信息失败:', error);
    }
};

// 消息处理器
const handleMessage = ({ from, message }) => {
    console.log('Information.vue 收到消息:', { from, message });
    console.log('当前目标用户ID:', userId.value);
    console.log('消息发送者ID:', from);
    console.log('当前用户ID:', currentUserId.value);
    
    // 检查消息是否来自当前聊天对象
    if (from !== userId.value) {
        console.log('消息不是来自当前聊天对象，跳过渲染');
        return;
    }
    
    console.log('添加对方消息到列表:', message);
    messages.value.push({
        from: 'other', // 标记为对方消息
        message: message,
        timestamp: new Date()
    });
    console.log('当前消息列表长度:', messages.value.length);
    
    // 注意：不需要在这里保存消息，因为 WebSocket 服务已经处理了
    // saveMessages(); // 注释掉，避免重复保存
    
    // 更新聊天记录（清除未读数）
    updateChatRecord(message, false); // 在聊天界面收到消息时，不增加未读数
    
    // 滚动到底部
    scrollToBottom();
};

// 发送消息
const sendMessage = () => {
    if (!newMessage.value.trim()) {
        return;
    }

    const messageContent = newMessage.value.trim();
    console.log('准备发送消息:', {
        to: userId.value,
        message: messageContent,
        from: currentUserId.value
    });

    // 使用 websocketService 发送消息
    const success = websocketService.sendMessage(userId.value, messageContent);

    if (success) {
        console.log('消息已发送到服务器');

        // 添加到本地消息列表
        messages.value.push({
            from: 'me', // 标记为自己的消息
            message: messageContent,
            timestamp: new Date()
        });

        // 注意：不需要在这里保存消息，因为 WebSocket 服务已经处理了
        // saveMessages(); // 注释掉，避免重复保存

        // 更新本地聊天记录
        updateChatRecord(messageContent);

        // 清空输入框
        newMessage.value = '';
        
        // 滚动到底部
        scrollToBottom();
    }
};

// 更新本地聊天记录
const updateChatRecord = (message, isReceived = false) => {
    try {
        const currentUserId = localStorage.getItem('user_id');
        if (!currentUserId) return;

        // 获取现有的聊天记录
        const chatRecords = JSON.parse(localStorage.getItem('chatRecords') || '{}');
        
        // 创建或更新聊天记录
        const chatKey = `${currentUserId}_${userId.value}`;
        const existingRecord = chatRecords[chatKey] || {};
        
        chatRecords[chatKey] = {
            userId: userId.value,
            nickname: userInfo.value.nickname,
            avatar_url: userInfo.value.avatar_url,
            lastMessage: message,
            lastMessageTime: new Date().toISOString(),
            unreadCount: isReceived ? (existingRecord.unreadCount || 0) + 1 : 0 // 在聊天界面时，清除未读数
        };

        // 保存到本地存储
        localStorage.setItem('chatRecords', JSON.stringify(chatRecords));
        console.log('聊天记录更新完成，未读数:', chatRecords[chatKey].unreadCount);
    } catch (error) {
        console.error('更新聊天记录失败:', error);
    }
};

// 滚动到底部
const scrollToBottom = async () => {
    await nextTick();
    if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
};

// 格式化时间
const formatTime = (timestamp) => {
    if (!timestamp) return '';
    
    const now = new Date();
    const time = new Date(timestamp);
    
    if (isNaN(time.getTime())) {
        return '';
    }
    
    const diff = now - time;
    
    // 十分钟内
    if (diff < 10 * 60 * 1000) {
        return '刚刚';
    }
    
    // 24小时内
    if (diff < 24 * 60 * 60 * 1000) {
        const hours = Math.floor(diff / (60 * 60 * 1000));
        const minutes = Math.floor(diff / (60 * 1000));
        
        if (hours === 0) {
            return `${minutes}分钟前`;
        } else {
            return `${hours}小时前`;
        }
    }
    
    // 本年内
    if (time.getFullYear() === now.getFullYear()) {
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${month}-${day}`;
    }
    
    // 超过本年
    const year = time.getFullYear();
    const month = String(time.getMonth() + 1).padStart(2, '0');
    const day = String(time.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 加载历史消息
const loadHistoryMessages = () => {
    try {
        const currentUserId = localStorage.getItem('user_id');
        if (!currentUserId || !userId.value) {
            console.log('缺少用户ID，无法加载历史消息');
            return;
        }

        console.log('开始加载历史消息:', { currentUserId, targetUserId: userId.value });

        // 首先尝试从本地存储加载消息
        const messageKey = `messages_${currentUserId}_${userId.value}`;
        const savedMessages = localStorage.getItem(messageKey);
        
        if (savedMessages) {
            const parsedMessages = JSON.parse(savedMessages);
            messages.value = parsedMessages.map(msg => ({
                ...msg,
                timestamp: new Date(msg.timestamp)
            }));
            console.log('从本地存储加载历史消息:', messages.value.length, '条');
        } else {
            console.log('本地存储中没有找到历史消息');
            // 如果没有本地存储的消息，尝试从全局聊天记录中获取最后一条消息
            const chatRecords = JSON.parse(localStorage.getItem('chatRecords') || '{}');
            const chatKey = `${currentUserId}_${userId.value}`;
            const chatRecord = chatRecords[chatKey];
            
            if (chatRecord && chatRecord.lastMessage) {
                console.log('从聊天记录中找到最后一条消息:', chatRecord.lastMessage);
                // 这里可以添加逻辑来获取完整的消息历史
                // 目前先显示最后一条消息作为示例
                messages.value = [{
                    from: 'other',
                    message: chatRecord.lastMessage,
                    timestamp: new Date(chatRecord.lastMessageTime)
                }];
            } else {
                console.log('没有找到任何历史消息');
                messages.value = [];
            }
        }
        
        console.log('历史消息加载完成，消息数量:', messages.value.length);
    } catch (error) {
        console.error('加载历史消息失败:', error);
        messages.value = [];
    }
};

// 保存消息到本地存储
const saveMessages = () => {
    try {
        const currentUserId = localStorage.getItem('user_id');
        if (!currentUserId || !userId.value) {
            console.log('缺少用户ID，无法保存消息');
            return;
        }

        // 保存消息到本地存储
        const messageKey = `messages_${currentUserId}_${userId.value}`;
        const messagesToSave = messages.value.map(msg => ({
            ...msg,
            timestamp: msg.timestamp.toISOString()
        }));
        localStorage.setItem(messageKey, JSON.stringify(messagesToSave));
        console.log('保存消息到本地存储:', messages.value.length, '条');
        console.log('保存的消息内容:', messagesToSave);
    } catch (error) {
        console.error('保存消息失败:', error);
    }
};

// 获取历史消息（为将来API做准备）
const fetchHistoryMessages = async () => {
    try {
        const currentUserId = localStorage.getItem('user_id');
        if (!currentUserId || !userId.value) return;

        // 这里可以添加API调用，例如：
        // const response = await axios.get(`http://1.14.98.17:8765/api/messages/${currentUserId}/${userId.value}`);
        // if (response.data.success) {
        //     messages.value = response.data.data.map(msg => ({
        //         ...msg,
        //         timestamp: new Date(msg.timestamp)
        //     }));
        // }

        // 目前使用本地存储
        loadHistoryMessages();
    } catch (error) {
        console.error('获取历史消息失败:', error);
        // 如果API失败，回退到本地存储
        loadHistoryMessages();
    }
};

onMounted(() => {
    console.log('Information.vue 组件挂载，开始初始化');
    console.log('目标用户ID:', userId.value);
    console.log('当前用户ID:', currentUserId.value);
    
    fetchUserInfo();
    fetchCurrentUserInfo();
    fetchHistoryMessages(); // 获取历史消息
    
    // 注册消息处理器
    websocketService.addMessageHandler(handleMessage);
    console.log('Information.vue 消息处理器注册完成');
    
    scrollToBottom();
    console.log('Information.vue 组件初始化完成');
});

onUnmounted(() => {
    // 移除消息处理器
    websocketService.removeMessageHandler(handleMessage);
});
</script>

<style lang="less" scoped>
.box {
    width: 100%;
    height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
    position: relative;

    .top {
        width: 100%;
        height: 100px;
        font-size: 32px;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 10;
        display: flex;
        align-items: center;
        background-color: #fff;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 0 20px;

        .back {
            width: 80px;
            height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;

            &:active {
                transform: scale(0.95);
            }
        }

        .user_pic {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            overflow: hidden;
            border: 2px solid #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }

        .user_name {
            margin-left: 20px;
            font-size: 28px;
            color: #333;
            font-weight: 500;
        }
    }

    .content {
        flex: 1;
        padding: 120px 20px 120px;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        
        &::-webkit-scrollbar {
            width: 6px;
        }
        
        &::-webkit-scrollbar-thumb {
            background-color: rgba(0, 0, 0, 0.2);
            border-radius: 3px;
        }

        .message_container {
            display: flex;
            align-items: flex-start;
            margin-bottom: 30px;
            gap: 12px;
        }

        .me_item {
            max-width: 70%;
            margin-left: auto;
            
            .message_bubble {
                background-color: #2780fe;
                color: #fff;
                padding: 16px 20px;
                border-radius: 20px 4px 20px 20px;
                position: relative;
                box-shadow: 0 2px 8px rgba(39, 128, 254, 0.2);

                .message_text {
                    word-break: break-word;
                    font-size: 28px;
                    line-height: 1.4;
                    margin-bottom: 8px;
                }

                .message_time {
                    font-size: 22px;
                    color: rgba(255, 255, 255, 0.7);
                    text-align: right;
                }
            }
        }

        .he_item {
            max-width: 70%;
            margin-right: auto;
            
            .message_bubble {
                background-color: #fff;
                color: #333;
                padding: 16px 20px;
                border-radius: 4px 20px 20px 20px;
                position: relative;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

                .message_text {
                    word-break: break-word;
                    font-size: 28px;
                    line-height: 1.4;
                    margin-bottom: 8px;
                }

                .message_time {
                    font-size: 22px;
                    color: #999;
                    text-align: left;
                }
            }
        }

        .me_avatar, .he_avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            overflow: hidden;
            flex-shrink: 0;
            border: 2px solid #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
    }

    .bottom {
        width: 100%;
        position: fixed;
        bottom: 0;
        left: 0;
        background-color: #fff;
        padding: 20px;
        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);

        .input_area {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 0 10px;

            .message_input {
                flex: 1;
                height: 80px;
                border: 2px solid #eee;
                border-radius: 40px;
                padding: 0 30px;
                font-size: 28px;
                outline: none;
                transition: all 0.3s;
                background-color: #f8f8f8;

                &:focus {
                    border-color: #2780fe;
                    background-color: #fff;
                }
            }

            .send_btn {
                width: 120px;
                height: 80px;
                background-color: #2780fe;
                color: #fff;
                border: none;
                border-radius: 40px;
                font-size: 28px;
                cursor: pointer;
                transition: all 0.3s;
                display: flex;
                align-items: center;
                justify-content: center;

                &:active {
                    transform: scale(0.95);
                    background-color: #1a6fd8;
                }
            }
        }
    }
}
</style>